<script setup lang="ts">
import {computed, onMounted, reactive, ref, watch} from "vue";
import {Loading, Refresh} from "@element-plus/icons-vue";
import {ElMessage, ElMessageBox, FormInstance} from "element-plus";
import {
  adminAddAdmin,
  adminDeleteAdmin,
  adminDisableAdmin,
  adminEditAdmin,
  adminGetAdminList,
  adminUnDisableAdmin,
} from "@/router/api"
import {adminUserStore} from "@/stores/adminStore";
import {useRouter} from "vue-router";

//是否显示删除人员信息
const isShowDelete = ref(true);
const router = useRouter();
const adminStore = adminUserStore();
const adminId = adminStore.adminInfo.id;
const addDialog = ref(false);
const editDialog = ref(false);
const tableData = ref<Array<{
  id: string;
  account: string;
  password: string;
  last_login_time: string;
  last_login_ip: string;
  status: string;
}>>([]);
const status = [// 借阅状态
  {text: '正常', value: '正常'},
  {text: '禁用', value: '禁用'},
  {text: '删除', value: '删除'},
];
// 表格行样式
const tableRowClassName = ({row}: { row: any }) =>
    row.status === '正常' ? 'success-row' : row.status === '禁用' ? 'warning-row' : '';
const filterStatus = (value: string, row: any) => {// 状态标签筛选函数
  return row.status === value;
};
const loading = ref(false)
const isRefreshing = ref(false);
// 模拟刷新动画
const handleRefresh = () => {
  getAdminLists()
  isRefreshing.value = true;
  loading.value = true;
  setTimeout(() => {
    isRefreshing.value = false;
    loading.value = false;
  }, 1000);
};
const showMessage = (type: any, message: any) => {// 显示消息提示
  ElMessage({
    type,
    message,
    duration: 1000,
  });
};
const rules = {
  account: [
    {required: true, message: '请输入账号', trigger: 'blur'},
    {min: 5, max: 10, message: '账号长度必须为5到10个字符', trigger: 'blur'},
    {pattern: /^admin[\w-]*$/, message: '账号必须以admin开头，可包含字母、数字、下划线或短横线', trigger: 'blur'}
  ],
  password: [
    {required: true, message: '请输入密码', trigger: 'blur'},
    {min: 2, max: 10, message: '密码长度在 2 到 10 个字符', trigger: 'blur'},
  ]
}
const mapData = (data: Array<any>) => {
  return data.map((item) => ({
    id: item.id,
    account: item.account,
    password: item.password,
    last_login_time: item.last_login_time,
    last_login_ip: item.last_login_ip,
    status: item.status === '1' ? '正常' : item.status === '0' ? '禁用' : '删除',
  }));
};
// 动态过滤表格数据
const filteredTableData = computed(() => {
  if (isShowDelete.value) {
    return tableData.value;
  }
  return tableData.value.filter((item) => item.status !== '删除');
});
// 获取用户列表
const getAdminLists = async () => {
  try {
    const response = await adminGetAdminList();
    if (Array.isArray(response)) {
      tableData.value = mapData(response);
    }
    console.log(tableData.value)
  } catch (error) {
    showMessage('error', "获取用户列表失败")
  }
}
// 禁用
const handleDisable = async (row: any) => {
  try {
    if (row.status === '正常') {
      // 如果当前状态正常，执行冻结操作
      await adminDisableAdmin(row.id);
      showMessage('success', "禁用成功");
    } else if (row.status === '禁用') {
      // 如果当前状态已冻结，执行解冻操作
      await adminUnDisableAdmin(row.id);
      showMessage('success', "禁用成功");
    }
    await getAdminLists()
  } catch (error) {
    showMessage('error', "禁用失败")
  }
}
// 删除操作
const handleDelete = (row: any) => {
  ElMessageBox({
    title: '删除用户',
    message: '你确定要删除该用户？',
    showCancelButton: true,
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    center: true,  // 中心对齐
  }).then(async () => {
    await adminDeleteAdmin(row.id)
    await getAdminLists()
    showMessage('success', "删除成功")
  })
      .catch(() => {
        showMessage('info', "已取消删除");
      });
};

//添加管理员
const addFormRef = ref<FormInstance>();
const addForm = reactive({
  account: '',
  password: '',
});
const handleAdd = async () => {
  await addFormRef.value?.validate(async (valid) => {
    if (valid) {
      try {
        const response = await adminAddAdmin(addForm);
        const {status} = response;
        if (status.toString() === 'warning') {
          showMessage('warning', '账号已存在！');
        } else {
          await getAdminLists();
          resetForm();
          addDialog.value = false;
          showMessage('success', '添加成功！');
        }
      } catch (error) {
        showMessage('error', '添加失败，请稍后再试！');
      }
    } else {
      showMessage('warning', '请确保所有字段都填写完整！');
    }
  });
};
const closeAddDialog = () => {// 关闭添加书籍的抽屉
  addDialog.value = false;
  resetForm();
};
const resetForm = () => {// 重置表单数据
  addFormRef.value?.resetFields();
}

//修改管理员
const editFormRef = ref<FormInstance>();
const editForm = reactive({
  id: '',
  account: '',
  password: '',
})
const openEdit = (row: any) => {
  editDialog.value = true;
  editForm.id = row.id;
  editForm.account = row.account;
}
const handleEdit = () => {
  editFormRef.value?.validate(async (valid) => {
    if (valid) {
      try {
        await adminEditAdmin(editForm);
        await getAdminLists();
        editDialog.value = false;
        editFormRef.value?.resetFields();
        editForm.account = ''
        editForm.password = ''
        showMessage("success", "编辑成功");
        if (editForm.id === adminId) {
          adminStore.logout();
          await router.replace('/login-register');
        }
      } catch (error) {
        showMessage("error", "编辑失败");
      }
    } else {
      showMessage("warning", "请确保所有字段都填写完整！");
    }
  });
}
// 监听 isShowDelete 的变化，动态刷新表格数据
watch(isShowDelete, async (newValue) => {
  if (newValue) {
    await getAdminLists(); // 如果显示删除状态的用户，重新获取数据
  }
});
onMounted(() => {
  getAdminLists()
})
</script>

<template>
  <div class="admin-container">
    <el-button @click="addDialog= true" type="primary" plain class="buttons">添加管理员</el-button>
    <el-switch
        v-model="isShowDelete"
        style="--el-switch-on-color: #13ce66;margin-left: 20px;"
    />
    <div class="refresh-container">
      <el-icon v-if="isRefreshing" class="loading-icon">
        <Loading/>
      </el-icon>
      <el-icon v-else class="refresh-icon">
        <Refresh @click="handleRefresh"/>
      </el-icon>
    </div>
  </div>
  <el-table :data="filteredTableData" border style="width: 100%" highlight-current-row
            v-loading="loading"
            :row-class-name="tableRowClassName">
    <el-table-column prop="account" label="账号" show-overflow-tooltip align="center"/>
    <el-table-column prop="last_login_time" label="登录时间" show-overflow-tooltip
                     align="center" width="180"/>
    <el-table-column prop="last_login_ip" label="登录地点" show-overflow-tooltip
                     align="center"/>
    <el-table-column prop="status" label="状态" :filters="status" :filter-method="filterStatus"
                     filter-placement="bottom-end" show-overflow-tooltip align="center" width="90">
      <template #default="scope">
        <el-tag
            :type="scope.row.status === '正常' ? 'success' : scope.row.status === '禁用' ? 'warning' : 'danger'"
            disable-transitions>
          {{ scope.row.status }}
        </el-tag>
      </template>
    </el-table-column>
    <el-table-column fixed="right" label="操作" show-overflow-tooltip align="center" width="200">
      <template #default="scope">
        <el-button size="small" @click="handleDisable(scope.row)" type="warning"
                   :plain="scope.row.status === '禁用'"
                   :disabled="scope.row.status === '删除' || scope.row.id === adminId||scope.row.account === 'admin'">
          {{ scope.row.status === '正常' ? '禁用' : '解除' }}
        </el-button>
        <el-button size="small" @click="openEdit(scope.row)" type="primary"
                   :disabled="scope.row.status === '删除'||scope.row.status === '禁用'">
          修改
        </el-button>
        <el-button :disabled="scope.row.id === adminId||scope.row.account === 'admin'" size="small"
                   @click="handleDelete(scope.row)" type="danger"
                   plain>
          删除
        </el-button>
      </template>
    </el-table-column>
  </el-table>
  <!-- 添加管理员弹窗 -->
  <el-dialog v-model="addDialog" title="添加管理员" width="500" center draggable>
    <el-form :model="addForm"
             ref="addFormRef"
             :rules="rules"
             status-icon
             scroll-to-error
             label-width="auto"
             size="default">
      <el-form-item label="请输入账号" prop="account">
        <el-input v-model="addForm.account" placeholder="请输入账号"/>
      </el-form-item>
      <el-form-item label="请输入密码" prop="password">
        <el-input v-model="addForm.password" placeholder="请输入密码"/>
      </el-form-item>
    </el-form>
    <template #footer>
      <div>
        <el-button @click="closeAddDialog">取消</el-button>
        <el-button type="primary" @click="handleAdd">添加</el-button>
      </div>
    </template>
  </el-dialog>
  <!-- 修改管理员弹窗 -->
  <el-dialog v-model="editDialog" title="修改管理员" width="500" center draggable>
    <el-form :model="editForm"
             ref="editFormRef"
             :rules="rules"
             status-icon
             scroll-to-error
             label-width="auto"
             size="default">
      <el-form-item label="请修改账号" prop="account">
        <el-input v-model="editForm.account" disabled placeholder="请修改账号"/>
      </el-form-item>
      <el-form-item label="请修改密码" prop="password">
        <el-input v-model="editForm.password" placeholder="请修改密码"/>
      </el-form-item>
    </el-form>
    <template #footer>
      <div>
        <el-button @click="editDialog= false">取消</el-button>
        <el-button type="primary" @click="handleEdit">修改</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style scoped>
.admin-container {
  width: 100%;
  display: flex;
  align-items: center;
  margin: 20px 0;
}

.refresh-container {
  margin-top: 4px;
  margin-left: 20px;
}

.loading-icon {
  color: #707581;
  font-size: 26px;
  animation: spin 1s infinite linear;
}

.refresh-icon {
  color: #707581;
  cursor: pointer;
  font-size: 26px;
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}
</style>
